package com.fyales.android.juhejoke.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.fyales.android.juhejoke.R;
import com.fyales.android.juhejoke.model.Course;
import com.fyales.android.juhejoke.model.Student;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Func1;

public class MapFlatFunctionDemoActivity extends AppCompatActivity {

    public List<String> courseList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_flat_function_demo);

        ListView lv = (ListView) findViewById(R.id.lv1);
        courseList = new ArrayList<>();
        final ArrayAdapter<String> baseAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,courseList);
        lv.setAdapter(baseAdapter);

        Subscriber<Course> subscriber = new Subscriber<Course>() {
            @Override
            public void onCompleted() {
                baseAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Course course) {
                courseList.add(course.getCourseName());
            }
        };

         Observable.from(initData())
                .flatMap(new Func1<Student, Observable<Course>>() {
                    @Override
                    public Observable<Course> call(Student student) {
                        return Observable.from(student.getCourse());
                    }
                })
                .subscribe(subscriber);


    }

    private List<Student> initData(){

        Course english = new Course("English");
        Course chinese = new Course("Chinese");
        Course history = new Course("History");
        Course math = new Course("Math");

        Student student1 = new Student("小明");
        student1.addCourse(english);
        student1.addCourse(history);
        student1.addCourse(math);

        Student student2 = new Student("小李");
        student2.addCourse(chinese);
        student2.addCourse(math);

        Student student3 = new Student("小白");
        student3.addCourse(english);
        student3.addCourse(chinese);
        student3.addCourse(history);

        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);

        return list;

    }
}
